package com.ruoyi.web.controller.cpsp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.mapper.CurrentPerformanceDataMapper;
import com.ruoyi.cpsp.service.DepartmentService;
import com.ruoyi.cpsp.service.DepartmentUserService;
import com.ruoyi.cpsp.service.EmployeeService;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author neu.xiangwenjuan
 * @date 2022/3/9 16:02
 */
@CrossOrigin
@RestController
@RequestMapping("/cpsp/employee")
public class EmployeeController {

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private DepartmentUserService departmentUserService;

    @Autowired
    private CurrentPerformanceDataMapper currentMapper;

    /**
     * 分页显示，一次几条数据。
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("获得所有人员信息")
    @RequestMapping(value = "/getAllEmployeeInfo", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getAllEmployeeInfo(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();
        // 调用这个方法一次，数据库中就有数据了，可以把这个方法注释掉，防止多次向数据库插入数据。
        // insertEmployeeToTable();

        PageHelper.startPage(pageNum,pageSize);

        List<EmployeeEntity> employeeList = new ArrayList<>();

        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            employeeList = employeeService.selectAll();
        }else if (role.equals("department")){
            employeeList = employeeService.selectEmployeesByDepartment(departmentId);
        }
        for (EmployeeEntity employees:employeeList) {
            employees.setAge(tranCardToAge(employees.getIdCard()));
        }

        PageInfo pageInfo = PageInfo.of(employeeList);

        return AjaxResult.success(pageInfo);
    }

    @ApiOperation("修改人员信息——班组和是否为生产岗位")
    @RequestMapping(value = "/updateEmployeeInfo", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult updateEmployeeInfo(Employee employee) {
        int count = employeeService.updateByPrimaryKeySelective(employee);
        // 根据record里面isDirectProducer的值来更新currentPerformanceData数据库。
        // 先根据身份证号查找current里面的数据，然后进行修改，然后再更新到表中。
        CurrentPerformanceData currentPerformanceData = currentMapper.selectDataByEmployeeCard(employee.getIdCard());
        // 更新累积绩效值
        if (employee.getIsDirectProducer() == 1) {
            // 生产者
            if ((currentPerformanceData.getCumulativeBase() + 100.0) > 1000) {
                currentPerformanceData.setIncreaseBase(1000 - currentPerformanceData.getCumulativeBase());
            }else {
                currentPerformanceData.setIncreaseBase(100.0);
            }
        }else {
            // 其他岗位
            if ((currentPerformanceData.getCumulativeBase() + 50.0) > 500) {
                currentPerformanceData.setIncreaseBase(500 - currentPerformanceData.getCumulativeBase());
            }else {
                currentPerformanceData.setIncreaseBase(50.0);
            }
        }
        // 更新其他值
        currentPerformanceData.setValueOfPunishment((currentPerformanceData.getCumulativeBase() + currentPerformanceData.getIncreaseBase()) * currentPerformanceData.getProportionOfPunishment());
        currentPerformanceData.setCurrentBase(currentPerformanceData.getCumulativeBase() + currentPerformanceData.getIncreaseBase() - currentPerformanceData.getValueOfPunishment());
        currentPerformanceData.setMoneyQuarter(currentPerformanceData.getCurrentBase() * 3);
        currentPerformanceData.setMoneyEveryMonth(currentPerformanceData.getCurrentBase());
        currentMapper.updateById(currentPerformanceData);
        if (count > 0) {
            return AjaxResult.success("修改成功！");
        }else {
            return AjaxResult.error("修改失败！");
        }
    }

    @ApiOperation("根据参数选择性筛选人员信息")
    @RequestMapping(value = "getInfoSelective",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getInfoSelective(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String department,String teamGroup, Integer isDirectProducer, String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<EmployeeEntity> list = employeeService.selectInfoSelective(department, teamGroup, isDirectProducer, name);
        for (EmployeeEntity employees:list) {
            employees.setAge(tranCardToAge(employees.getIdCard()));
        }
        PageInfo pageInfo = PageInfo.of(list);
        return AjaxResult.success(pageInfo);
    }

    @ApiOperation("根据id得到员工信息")
    @RequestMapping(value = "getEmployeeById",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getEmployeeById(Integer id) {
        EmployeeEntity employee = employeeService.getById(id);
        if (employee != null) {
            employee.setAge(tranCardToAge(employee.getIdCard()));
            return AjaxResult.success(employee);
        }else {
            return AjaxResult.error("id无效！");
        }
    }

    @ApiOperation("根据姓名得到员工信息")
    @RequestMapping(value = "getEmployeeByName",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getEmployeeByName(String name) {
        List<EmployeeEntity> list = employeeService.selectByName(name, 1);
        for (EmployeeEntity employees:list) {
            employees.setAge(tranCardToAge(employees.getIdCard()));
        }
        return AjaxResult.success(list);
    }

    @ApiOperation("根据工号得到员工信息")
    @RequestMapping(value = "getEmployeeByJobNumber",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getEmployeeByJobNumber(String jobNumber) {
        EmployeeEntity employee = employeeService.selectByJobNumber(jobNumber);
        employee.setAge(tranCardToAge(employee.getIdCard()));
        return AjaxResult.success(employee);
    }

    @ApiOperation("根据部门获得人员信息")
    @RequestMapping(value = "getInfoByDepartment",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getInfoByDepartment(@RequestParam(required = true) String department) {
        List<EmployeeEntity> list = employeeService.selectInfoSelective(department,null,null,null);
        for (EmployeeEntity employees:list) {
            employees.setAge(tranCardToAge(employees.getIdCard()));
        }
        return AjaxResult.success(list);
    }

    @ApiOperation("根据请求获得登录员工的基本信息")
    @RequestMapping(value = "getLoginEmployeeInfo",method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getLoginEmployeeInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("User", sysUser);
        ajaxResult.put("department", dept);
        return AjaxResult.success(ajaxResult);
    }

    @ApiOperation("条件查询职工信息")
    @RequestMapping(value = "findEmployee",method = RequestMethod.GET)
    public AjaxResult findEmployee(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10")Integer pageSize,
                               String departmentId,
                               String teamGroupId,
                               String name){

        return AjaxResult.success(employeeService.findEmployee(pageNum, pageSize, departmentId, teamGroupId, name));
    }

    @ApiOperation("修改职工班组和岗位类型")
    @RequestMapping(value = "updateEmployeeTeamAndPosition",method = RequestMethod.GET)
    public AjaxResult updateEmployeeTeamAndPosition(Integer employeeId,
                               String teamGroupName,
                               String positionType){

        if (employeeService.updateEmployeeTeamAndPosition(employeeId, teamGroupName, positionType) > 0)
            return AjaxResult.success("修改成功");
        else

            return AjaxResult.error("修改失败");
    }

    @ApiOperation("修改职工是否在岗45天")
    @RequestMapping(value = "updateEmployeeIs45Days",method = RequestMethod.GET)
    public AjaxResult updateEmployeeIs45Days(Integer employeeId,
                                         Integer is45Days){

        if (employeeService.updateEmployeeIs45Days(employeeId, is45Days) > 0)
            return AjaxResult.success("修改成功");
        else
            return AjaxResult.error("修改失败");
    }

    /**
     * 2022/04/20
     * 班组和部分修改
     */
    @ApiOperation("查询班组信息及分主管的姓名")
    @GetMapping(value = "findTeamGroupAndName")
    public AjaxResult findTeamGroupAndName(String departmentId){
        return AjaxResult.success(employeeService.findTeamGroupAndName(departmentId));
    }

    /**
     * 提醒：在班组表中记录分管和主管使用身份证号。
     * @param id
     * @param branchManagerIdCard
     * @param mainManagerIdCard
     * @return
     */
    @ApiOperation("修改班组的主管id，分管id")
    @GetMapping(value = "updateTeamGroup")
    public AjaxResult updateTeamGroup(Integer id,
                                      String teamGroupName,
                                      String branchManagerIdCard,
                                      String mainManagerIdCard){
        return AjaxResult.success(employeeService.updateTeamGroup(id,teamGroupName, branchManagerIdCard, mainManagerIdCard));
    }

    @ApiOperation("根据班组id，删除班组")
    @PostMapping(value = "deleteTeamGroup")
    public AjaxResult deleteTeamGroup(Integer id){
        employeeService.updateTeamGroup(id);
        return AjaxResult.success(employeeService.deleteTeamGroup(id));
    }



    @ApiOperation("添加班组")
    @PostMapping(value = "addTeamGroup")
    public AjaxResult addTeamGroup(TeamGroup teamGroup){
        return AjaxResult.success(employeeService.addTeamGroup(teamGroup));
    }

    @ApiOperation("查询所有部门，按星级从高到底排序")
    @GetMapping(value = "selectDepartmentOrder")
    public AjaxResult selectDepartmentOrder(){
        return AjaxResult.success(departmentService.selectDepartmentOrder());
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("增加员工")
    @PostMapping("/insertEmployee")
    public AjaxResult insertEmployee(@RequestBody Employee employee){
        // TODO 修改，查看员工之前是否存在，如果存在，修改状态即可。
        EmployeeEntity employeeHistory = employeeService.selectByCard(employee.getIdCard());
        if (employeeHistory == null) {
            employee.setState(0);
            if (employee.getIdCard().length() == 18 && employeeService.insertEmployee(employee)){
                CurrentPerformanceData currentData = currentMapper.selectFirst();
                CurrentPerformanceData currentPerformanceData = new CurrentPerformanceData();
                currentPerformanceData.setEmployeeIdCard(employee.getIdCard());
                currentPerformanceData.setYear(currentData.getYear());
                currentPerformanceData.setQuarter(currentData.getQuarter());
                if (employee.getIsDirectProducer() == null || employee.getIsDirectProducer() == 2 || employee.getIsDirectProducer() == 3) {
                    currentPerformanceData.setIncreaseBase(50);
                    currentPerformanceData.setCumulativeBase(100);
                }else {
                    currentPerformanceData.setIncreaseBase(100);
                    currentPerformanceData.setCumulativeBase(200);
                }
                currentPerformanceData.setProportionOfPunishment(0.0);
                currentPerformanceData.setValueOfPunishment(0.0);
                currentPerformanceData.setCurrentBase(currentPerformanceData.getCumulativeBase() + currentPerformanceData.getIncreaseBase());
                currentPerformanceData.setMoneyEveryMonth(currentPerformanceData.getCurrentBase());
                currentPerformanceData.setMoneyQuarter(3 * currentPerformanceData.getCurrentBase());
                if (currentMapper.insert(currentPerformanceData) ==1) {
                    return AjaxResult.success("员工添加成功！");
                }else {
                    return AjaxResult.error("添加绩效失败！");
                }
            }else {
                return AjaxResult.error("员工添加失败！");
            }
        }else {
            if(employeeHistory.getState() == 2){
                // 更新信息
                Employee employee1 = new Employee();
                employee1.setId(employeeHistory.getId());
                employee1.setName(employee.getName());
                employee1.setIdCard(employee.getIdCard());
                employee1.setDepartmentId(employee.getDepartmentId());
                if (employee.getPositionType() != null) {
                    employee1.setPositionType(employee.getPositionType());
                }
                if (employee.getIsDirectProducer() != null) {
                    employee1.setIsDirectProducer(employee.getIsDirectProducer());
                }
                if (employee.getTeamGroupId() != null) {
                    employee1.setTeamGroupId(employee.getTeamGroupId());
                }
                employee1.setState(0);
                if (employeeService.updateEmployee(employee1)) {
                    CurrentPerformanceData currentData = currentMapper.selectFirst();
                    CurrentPerformanceData currentPerformanceData = new CurrentPerformanceData();
                    currentPerformanceData.setEmployeeIdCard(employee.getIdCard());
                    currentPerformanceData.setYear(currentData.getYear());
                    currentPerformanceData.setQuarter(currentData.getQuarter());
                    currentPerformanceData.setCumulativeBase(100);
                    if (employee.getIsDirectProducer() == null || employee.getIsDirectProducer() == 2 || employee.getIsDirectProducer() == 3) {
                        currentPerformanceData.setIncreaseBase(50);
                    }else {
                        currentPerformanceData.setIncreaseBase(100);
                    }
                    currentPerformanceData.setProportionOfPunishment(0.0);
                    currentPerformanceData.setValueOfPunishment(0.0);
                    currentPerformanceData.setCurrentBase(currentPerformanceData.getCumulativeBase() + currentPerformanceData.getIncreaseBase());
                    currentPerformanceData.setMoneyEveryMonth(currentPerformanceData.getCurrentBase());
                    currentPerformanceData.setMoneyQuarter(3 * currentPerformanceData.getCurrentBase());
                    if (currentMapper.insert(currentPerformanceData) ==1) {
                        return AjaxResult.success("员工添加成功！");
                    }else {
                        return AjaxResult.error("添加绩效失败！");
                    }
                }
            }
        }
        return AjaxResult.error("该员工已存在！");
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("删除员工")
    @DeleteMapping("{id}")
    public AjaxResult deleteEmployee(@PathVariable Integer id){
        if(employeeService.updateEmployeeState(id, 2) > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("修改员工")
    @PutMapping("/updateEmployee")
    public AjaxResult updateEmployee(@RequestBody Employee employee){
        if(employeeService.updateEmployee(employee)){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("批量修改员工班组")
    @PutMapping("/updateGroupBatch")
    public AjaxResult updateGroupBatch(@RequestParam List<Integer> ids,@RequestParam String teamGroupId){
        if(employeeService.updateGroupBatch(ids, teamGroupId)){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * @author ZhangHengWei
     */
    @ApiOperation("员工更换部门")
    @PutMapping("/transDepartment")
    public AjaxResult transDepartment(@RequestParam Integer id,@RequestParam String departmentId){
        if(employeeService.transDepartment(id, departmentId)){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     *   接口类写到上面
     *   工具类
     *   身份证号转出age
     */

    private int tranCardToAge(String idCard) {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH)+1;
        int dayNow = cal.get(Calendar.DATE);

        int year = Integer.valueOf(idCard.substring(6, 10));
        int month = Integer.valueOf(idCard.substring(10,12));
        int day = Integer.valueOf(idCard.substring(12,14));

        if ((month < monthNow) || (month == monthNow && day<= dayNow) ){
            age = yearNow - year;
        }else {
            age = yearNow - year-1;
        }
        return age;
    }

    /**
     * 插入部门信息
     * @return
     */
    private boolean insertDepartmentToTable()
    {
        // 得到所有部门信息
        Object object = testPost("department", new DepartmentFromCompany());
        String json = JSON.toJSONString(object);
        DepartmentFromCompany departmentFromCompany = JSONObject.parseObject(json,DepartmentFromCompany.class);
        DepartmentFromCompanyData[] departmentDatas = departmentFromCompany.getData();

        boolean res = true;
        for (DepartmentFromCompanyData departmentData : departmentDatas)
        {
            String  departmentId   = departmentData.getId(),
                    departmentName = departmentData.getDWMC();

            Department insertDepartment = new Department(departmentId, departmentName);

            // 插入 department
            res = res && departmentService.insert(insertDepartment);
        }

        return res;
    }

    /**
     * 插入员工数据
     * @return
     */
    public boolean insertEmployeeToTable()
    {
        // 得到所有用户信息
        Object object = testPost("user",new EmployeeFromCompany());
        String json = JSON.toJSONString(object);
        EmployeeFromCompany employeeFromCompany = JSONObject.parseObject(json, EmployeeFromCompany.class);
        EmployeeFromCompanyData[] employeeDatas = employeeFromCompany.getData();

        int dateFlag    = getPassDaySeason(new Date());
        boolean        res         = true;

        for (EmployeeFromCompanyData employeeData : employeeDatas)
        {

            String  name            = employeeData.getName(),
                    idCard          = employeeData.getIdcard(),
                    jobNumber       = employeeData.getId(),
                    positionType    = employeeData.getPosition(),
                    departmentId    = employeeData.getDwh_id();

            Integer is45Days = dateFlag > getCountBetweenTwoDates(employeeData.getStart(), new Date()) ? dateFlag : getCountBetweenTwoDates(employeeData.getStart(), new Date());

            Employee insertEmployee = new Employee(name, idCard, jobNumber, is45Days, positionType, departmentId);

            res = res && employeeService.submitAllInfo(insertEmployee);
        }

        return res;
    }

    // 得到两个日期之间的差值
    public int getCountBetweenTwoDates(String start, Date data) {
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        int day = 0;
        try{
            Date star = dft.parse(start);
            Long startTime = star.getTime();
            Long endTime = data.getTime();
            Long num = endTime - startTime;
            day =(int)(num/24/60/60/1000);
        }catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }
    // 下面四个方法用来获得当前季度已经度过多少天
    public int getPassDaySeason(Date date) {
        int day = 0;
        Date[] seasonDates = getSeasonDate(date);

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int month = c.get(Calendar.MONTH);

        if (month == Calendar.JANUARY || month == Calendar.APRIL || month == Calendar.JULY || month == Calendar.OCTOBER ) {
            day = getPassDayOfMonth(seasonDates[0]);
        }else if (month == Calendar.FEBRUARY || month == Calendar.MAY || month == Calendar.AUGUST || month == Calendar.NOVEMBER ) {
            day = getPassMaxDayOfMonth(seasonDates[0]) + getPassDayOfMonth(seasonDates[1]);
        }else if (month == Calendar.MARCH || month == Calendar.JUNE || month == Calendar.SEPTEMBER || month == Calendar.DECEMBER ) {
            day = getPassMaxDayOfMonth(seasonDates[0]) + getPassMaxDayOfMonth(seasonDates[1]) + getPassDayOfMonth(seasonDates[2]);
        }
        return day;
    }
    private int getPassDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_MONTH);
    }
    private int getPassMaxDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);
    }
    private Date[] getSeasonDate(Date date) {
        Date[] season = new Date[3];

        Calendar c = Calendar.getInstance();
        c.setTime(date);

        int nSeason = getSeason(date);
        if (nSeason == 1) {
            c.set(Calendar.MONTH, Calendar.JANUARY);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.FEBRUARY);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.MARCH);
            season[2] = c.getTime();
        }else if (nSeason == 2) {
            c.set(Calendar.MONTH, Calendar.APRIL);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.MAY);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.JUNE);
            season[2] = c.getTime();
        }else if (nSeason == 3) {
            c.set(Calendar.MONTH, Calendar.JULY);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.AUGUST);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.SEPTEMBER);
            season[2] = c.getTime();
        }else if (nSeason == 4) {
            c.set(Calendar.MONTH, Calendar.OCTOBER);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.NOVEMBER);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.DECEMBER);
            season[2] = c.getTime();
        }
        return season;
    }
    public int getSeason(Date date) {
        int season = 0;
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int month = c.get(Calendar.MONTH);
        switch (month) {
            case Calendar.JANUARY:
            case Calendar.FEBRUARY:
            case Calendar.MARCH:
                season = 1;
                break;
            case Calendar.APRIL:
            case Calendar.MAY:
            case Calendar.JUNE:
                season = 2;
                break;
            case Calendar.JULY:
            case Calendar.AUGUST:
            case Calendar.SEPTEMBER:
                season = 3;
                break;
            case Calendar.OCTOBER:
            case Calendar.NOVEMBER:
            case Calendar.DECEMBER:
                season = 4;
                break;
            default:
                break;
        }
        return season;
    }

    public Object testPost(String param1, Object object) {
        String url = "http://47.94.148.26:8002/jx/";
        String urlData = "http://47.94.148.26:8002/jx/api/";
        try{
            URL path = new URL(url);
            // 获取token
            HttpURLConnection connection = (HttpURLConnection) path.openConnection();
            String token = connection.getHeaderField("Set-Cookie").substring(10,74);
            // 设置请求headers和cookies
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type","multipart/form-data; charset=UTF-8");
            headers.add("X-CSRFToken",token);
            headers.add(HttpHeaders.COOKIE,"csrftoken="+token);
            headers.add(HttpHeaders.COOKIE,"payroll=apiuser");
            // 设置请求参数
            MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
            map.add("csrfmiddlewaretoken",token);
            map.add("object",param1);
            map.add("id","all");

            HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<>(map,headers);
            ResponseEntity<Object> responseEntity = restTemplate.exchange(urlData, HttpMethod.POST, formEntity, Object.class);


            object = responseEntity.getBody();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }


}
